// File Name: oled_ctrl.c
// Author: kukukukuku~
// Date: 2024-12-23

#include "apm32f00x_gpio.h"
#include "./OLED/inc/oled_ctrl.h"

/**
 * @brief   OLED延时
 * @param   t:  时钟周期数量
 * @retval  None
 * @note    静态
*/
static void oled_delay(uint32_t t)
{
    while(t--)
        __nop();
}


/**
 * @brief   OLED起始信号
 * @param   None
 * @retval  None
 * @note    静态
*/
static void oled_start(void)
{
    OLED_SCL_H;
    OLED_SDA_H;
    oled_delay(1);
    
    OLED_SDA_L;
    OLED_SCL_L;
    oled_delay(1);
}


/**
 * @brief   OLED停止信号
 * @param   None
 * @retval  None
 * @note    静态
*/
static void oled_stop(void)
{
    OLED_SCL_H;
    OLED_SDA_L;
    oled_delay(1);
    
    OLED_SDA_H;
    oled_delay(1);
}


/**
 * @brief   OLED等待应答
 * @param   None
 * @retval  None
 * @note    静态
*/
static void oled_wait_ack(void)
{
    OLED_SCL_L;
    oled_delay(1);
    
    OLED_SCL_H;
    oled_delay(1);
    
    OLED_SCL_L;
    oled_delay(1);
}


/**
 * @brief   OLED发送一个字节
 * @param   byte:   要发送的字节
 * @retval  None
 * @note    静态
*/
static void oled_send_byte(const uint8_t byte)
{
    OLED_SCL_L;
    oled_delay(1);
    
    for(uint8_t i = 0; i < 8; i++)
    {
        byte << i & 0x80 ? OLED_SDA_H : OLED_SDA_L;
        oled_delay(1);
        
        OLED_SCL_H;
        oled_delay(1);
        
        OLED_SCL_L;
        oled_delay(1);
    }
}


/**
 * @brief   OLED发送数据/命令
 * @param   data:   要发送的数据/命令
 * @param   mode:   发送模式
 *                  @arg OLED_SEND_CMD:     发送命令
 *                  @arg OLED_SEND_DATA:    发送数据
 * @retval  None
 * @note    None
*/
void oled_send_data(const uint8_t data, const OLED_SEND_MODE_T mode)
{
    oled_start();
    
    oled_send_byte(0x78);
    oled_wait_ack();
    
    oled_send_byte(mode == OLED_SEND_CMD ? 0x00 : 0x40);
    oled_wait_ack();
    
    oled_send_byte(data);
    oled_wait_ack();
    
    oled_stop();
}
